'use client'

import { useEffect, useState } from 'react'
import RegionTable from './components/RegionTable'
import RegionForm from './components/RegionForm'
import { Region } from '@/app/types/region'

export default function RegionsPage() {
  const [regions, setRegions] = useState<Region[]>([])
  const [editingRegion, setEditingRegion] = useState<Region | null>(null)
  const [isFormOpen, setIsFormOpen] = useState(false)
  const [currentParentCode, setCurrentParentCode] = useState<string>('')
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    fetchRegions()
  }, [])

  const fetchRegions = async () => {
    try {
      const response = await fetch('/api/regions')
      const data = await response.json()
      setRegions(Array.isArray(data) ? data : [])
    } catch (error) {
      console.error('获取行政区划失败:', error)
      setRegions([])
    } finally {
      setIsLoading(false)
    }
  }

  const handleAddRegion = async (regionData: Omit<Region, 'id' | 'createdAt' | 'updatedAt'>) => {
    try {
      const response = await fetch('/api/regions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(regionData),
      })
      const newRegion = await response.json()
      setRegions([...regions, newRegion])
      setIsFormOpen(false)
    } catch (error) {
      console.error('添加行政区划失败:', error)
    }
  }

  const handleEditRegion = async (regionData: Region) => {
    try {
      const response = await fetch(`/api/regions/${regionData.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(regionData),
      })
      const updatedRegion = await response.json()
      setRegions(regions.map(r => r.id === updatedRegion.id ? updatedRegion : r))
      setEditingRegion(null)
      setIsFormOpen(false)
    } catch (error) {
      console.error('更新行政区划失败:', error)
    }
  }

  const handleDeleteRegion = async (id: string) => {
    try {
      await fetch(`/api/regions/${id}`, { method: 'DELETE' })
      setRegions(regions.filter(region => region.id !== id))
    } catch (error) {
      console.error('删除行政区划失败:', error)
    }
  }

  const loadChildren = async (parentCode: string) => {
    try {
      const response = await fetch(`/api/regions?parentCode=${parentCode}`);
      if (!response.ok) {
        throw new Error('加载失败');
      }
      const data = await response.json();
      return data;
    } catch (error) {
      console.error('加载子节点失败:', error);
      return [];
    }
  };

  if (isLoading) return <div className="text-white">加载中...</div>

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-semibold text-white">行政区划管理</h1>
        <button
          onClick={() => {
            setEditingRegion(null)
            setIsFormOpen(true)
          }}
          className="bg-[#1e3a8a] text-white px-4 py-2 rounded-md hover:bg-[#1e3a8a]/80 transition-colors"
        >
          添加区划
        </button>
      </div>

      <RegionTable
        regions={regions}
        onEdit={(region) => {
          setEditingRegion(region)
          setIsFormOpen(true)
        }}
        onDelete={handleDeleteRegion}
        onAddSub={(parentCode) => {
          setCurrentParentCode(parentCode)
          setEditingRegion(null)
          setIsFormOpen(true)
        }}
        onLoadChildren={loadChildren}
      />

      {isFormOpen && (
        <RegionForm
          region={editingRegion}
          parentCode={currentParentCode}
          onSubmit={async (region) => {
            if (editingRegion) {
              await handleEditRegion(region as Region)
            } else {
              await handleAddRegion(region)
            }
          }}
          onClose={() => {
            setIsFormOpen(false)
            setEditingRegion(null)
            setCurrentParentCode('')
          }}
        />
      )}
    </div>
  )
} 